package fid

import (
	"fmt"

	"gitee.com/gaoguangting/fid/session"
	"github.com/ilisin/configuration"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"github.com/sirupsen/logrus"
)

var RoutePrefix = "SC"

type Fid struct {
	config         *Config
	ec             *echo.Echo
	sessionManager *session.Manager
	// sessionManager *SessionManager

	protos []*ControllerProto
}

func newFid() *Fid {
	f := &Fid{
		// config: defaultConfig(),
		ec: echo.New(),
	}
	return f
}

func New() *Fid {
	return newFid()
}

func (f *Fid) SetConfig(cfg Config) {
	f.config = &cfg
}

func (f *Fid) setHttpHandler() {
	f.ec.POST(f.config.Path, f.echoRouter)
}

func (f *Fid) parseConfig() {
	err := configuration.Var(&f.config)
	if err != nil {
		logrus.Error(err)
		fmt.Println("parse config error[%v]", err)
	}
}

func (f *Fid) setMiddleware() {
	f.ec.Use(middleware.CORS())
}

func (f *Fid) Start() error {
	if f.config == nil {
		f.parseConfig()
	}
	f.setHttpHandler()
	f.setMiddleware()
	f.sessionStart()
	err := f.ec.Start(fmt.Sprintf("%v:%v", f.config.Host, f.config.Port))
	if err != nil {
		fmt.Printf("fid server start error :[%v]", err)
	}
	return err
}

func (f *Fid) Echo() *echo.Echo {
	return f.ec
}
